/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/
#include <QtCore>
#include <QDomDocument>
#include <QScriptValue>
#include <globals.h>

#include "meniu.h"

//---------------------------------------------------------------------------
static char * mtrans(char *SS, char Ordin)
{
char F[10][6] = {"una", "doua","trei","patru","cinci","sase","sapte","opt","noua","zece"};
char M[10][6] = {"un", "doi","trei","patru","cinci","sase","sapte","opt","noua","zece"};
static char Sir[30];
memset(Sir,0,30);
   if ((SS[0] != ' ') && (SS[0] != '0')){
      strcpy(Sir,F[SS[0]-49]);
      if (SS[0] == '1')
         strcat(Sir,"suta");
      else
         strcat(Sir,"sute");
   }
   if ((SS[1] != '0') &&(SS[1] != ' ')){
      if (SS[1] != '1'){
         strcat(Sir,F[SS[1]-49]);
         strcat(Sir,"zeci");
         if (SS[2] != '0')
            strcat(Sir,"si");
         if (SS[2] != '0')
            if (SS[2] != '1')
               if (Ordin != 1)
                  strcat(Sir,F[SS[2]-49]);
               else
                   strcat(Sir,M[SS[2]-49]);
            else
               strcat(Sir,"unu");
      }
      else{
           if ((SS[2] != '0') &&(SS[2] != ' ')){
              strcat(Sir,M[SS[2]-49]);
              strcat(Sir,"sprezece");
           }
           if ((SS[1] == '1') &&(SS[2] == '0'))
              strcat(Sir,"zece");
      }
   }
   else
        if (SS[2] !='0' &&SS[2] !=' '){
           switch (Ordin){
                  case 3:if (SS[2] =='2')
                            strcat(Sir,F[SS[2]-49]);
                         else
                            strcat(Sir,M[SS[2]-49]);
                         break;
                  case 2:strcat(Sir,F[SS[2]-49]);
                         break;
                  case 1:strcat(Sir,M[SS[2]-49]);
                         break;
           }
      }

return Sir;
}

static QScriptValue NumToStr(QScriptContext *context, QScriptEngine *engine)
{
	if (context->argumentCount() != 1)
		return engine->undefinedValue();
	double pr=context->argument(0).toNumber();
        int pr1 = (int)(qRound(pr*100));
        int prt = pr1/100;
        int  rest = pr1 % 100;
        char Suma[15];
        char Sir[120];
        memset (Sir,0,120);
        memset (Suma,0,15);
        char ZZ[4];
        memset(ZZ,0,4);
        sprintf(Suma,"%ld",prt);
        int L = strlen(Suma);
        int P = L%3;
        if (!P)
           P=3;
           strncpy (ZZ,Suma,P);
           if (P!=3)
              sprintf(ZZ,"%3d",atoi(ZZ));
           if (L>6){
              strcpy(Sir,mtrans(ZZ,3));
              if (atoi(ZZ)>1)
                 strcat(Sir," milioane ");
              else
                 strcat(Sir," milion ");
              strncpy (ZZ,&Suma[P],3);
              strcat(Sir,mtrans(ZZ,2));
              if (atoi(ZZ)>1)
                 strcat(Sir," mii ");
              else
                  if (atoi(ZZ)== 1)
                     strcat(Sir," mie ");
              strncpy (ZZ,&Suma[P+3],3);
              strcat(Sir,mtrans(ZZ,1));
              if (rest != 0)
	              strcat(Sir," lei si ");
                      else
                      strcat(Sir," lei");
              goto xx;
           }
           if (L>3){
              strcpy(Sir,mtrans(ZZ,2));
              if (atoi(ZZ)>1)
                 strcat(Sir," mii ");
              else
                 strcat(Sir," mie ");
              strncpy (ZZ,&Suma[P],3);
              strcat(Sir,mtrans(ZZ,1));
               if (rest != 0)
	              strcat(Sir," lei si ");
                      else
                      strcat(Sir," lei");
              goto xx;
           }
           strcpy(Sir,mtrans(ZZ,1));
            if (rest != 0)
	              strcat(Sir," lei si ");
                      else
                      strcat(Sir," lei");
xx:
        char Sirrest[120];
        memset (Sirrest,0,120);
        if (rest != 0){
        memset(ZZ,0,4);
        sprintf(Suma,"%ld",rest);
        L = strlen(Suma);
        P = L%3;
        if (!P)
           P=3;
        strncpy (ZZ,Suma,P);
        if (P!=3)
           sprintf(ZZ,"%3d",atoi(ZZ));
        if (L>6){
           strcpy(Sirrest,mtrans(ZZ,3));
           if (atoi(ZZ)>1)
              strcat(Sirrest," milioane ");
           else
              strcat(Sirrest," milion ");
           strncpy (ZZ,&Suma[P],3);
           strcat(Sir,mtrans(ZZ,2));
           if (atoi(ZZ)>1)
              strcat(Sirrest," mii ");
           else
              if (atoi(ZZ)== 1)
                 strcat(Sirrest," mie ");
           strncpy (ZZ,&Suma[P+3],3);
           strcat(Sirrest,mtrans(ZZ,1));
           strcat(Sirrest," bani");
           goto yy;
        }
        if (L>3){
                strcpy(Sirrest,mtrans(ZZ,2));
                if (atoi(ZZ)>1)
                   strcat(Sirrest," mii ");
                else
                   strcat(Sirrest," mie ");
                strncpy (ZZ,&Suma[P],3);
                strcat(Sirrest,mtrans(ZZ,1));
                strcat(Sirrest," bani");
                goto yy;
        }
        strcpy(Sirrest,mtrans(ZZ,1));
        strcat(Sirrest," bani");
        }
        else
           strcat(Sirrest,"");
        yy:
        strcat(Sir,Sirrest);
        return QScriptValue(engine, QString(Sir));
}

inline void initMyResource()
{
	Q_INIT_RESOURCE(meniuRapoarte);
}

MeniuRapoarte::MeniuRapoarte(QObject *parent):QObject(parent)
{
	initMyResource();
	QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_LINUX) | defined(Q_OS_X11)
	pluginsDir.cdUp();
	pluginsDir.cd("share");
	pluginsDir.cd("kontAMabil");
#elif defined(Q_OS_MAC)
	pluginsDir.cdUp();
#endif
	pluginsDir.cd("rapoarte");
	parseDir(pluginsDir);
}

void MeniuRapoarte::parseDir(QDir dir)
{
        foreach(QString subdir, dir.entryList(QDir::Dirs))
        {
                if (subdir=="." || subdir=="..")
                        continue;
                parseDir(dir.absolutePath()+"/"+subdir);
        }
        foreach(QString subdir, dir.entryList(QStringList()<<"*.bdrt",QDir::Files))
        {
                QDomDocument doc;
		QFile file(dir.absolutePath()+"/"+subdir);
		if (!file.open(QIODevice::ReadOnly))
			continue;

		if (!doc.setContent(&file))
		{
			file.close();
			continue;
		}
		file.close();

		QDomElement docElem = doc.documentElement().firstChildElement("properties");
		if (docElem.isNull())
			continue;

		m_menus<<Report::domToVariant(docElem.firstChildElement("menus")).toStringList();
		QIcon icon=Report::domToVariant(docElem.firstChildElement("icon")).value<QPixmap>();
		QString description=Report::domToVariant(docElem.firstChildElement("description")).toString();
		QString recommends=Report::domToVariant(docElem.firstChildElement("recommends")).toString();
		int menuGroup=Report::domToVariant(docElem.firstChildElement("menuGroup")).toInt();
		foreach(QString menu, Report::domToVariant(docElem.firstChildElement("menus")).toStringList())
		{
			m_rapoarte[menu].file=dir.absolutePath()+"/"+subdir;
			m_rapoarte[menu].icon=icon;
			m_rapoarte[menu].description=description;
			m_rapoarte[menu].recommends=recommends;
			m_rapoarte[menu].menuGroup=menuGroup;
		}
	}
}

KontAMabilWindow * MeniuRapoarte::createWidget(QWidget * /*parent*/)
{
	return 0;
}

QIcon MeniuRapoarte::icon(const QString & name)
{
	if (m_rapoarte[name].icon.isNull())
		return QIcon(":/meniuRapoarte/report.png");
	else
		return m_rapoarte[name].icon;
}

QString MeniuRapoarte::querys()
{
	return QString();
}

int MeniuRapoarte::order()
{
	return INT_MAX;
}

int MeniuRapoarte::menuGroup(const QString & name)
{
	return m_rapoarte[name].menuGroup;
}

QString MeniuRapoarte::toolTip(const QString & name)
{
	return m_rapoarte[name].tooltip;
}

QString MeniuRapoarte::name()
{
	return "meniurapoarte";
}

QString MeniuRapoarte::version()
{
	return "0.1";
}

QString MeniuRapoarte::depends()
{
	return "login";
}

QString MeniuRapoarte::recommends()
{
	return "Contabilitate|Gestiune|Salarii";
}

QString MeniuRapoarte::description(const QString & name)
{
	return m_rapoarte[name].description;
}

void MeniuRapoarte::exec(const QString & menu)
{
	Report::ReportInterface * report=m_reportEngine.loadReport(m_rapoarte[menu].file);
	if (!report)
		return;
	report->setDatabase(defaultDatabase()->database());
	report->setGlobalObjects(defaultDatabase()->children());
	const QMap<QString, QVariant> gvs=kontAMabil()->globalValues();
	foreach(QString key, gvs.keys())
		report->setReportGlobalValue(key,gvs[key]);

	report->setReportFunction("numarInLitere", ::NumToStr, 1);
	QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN32) | defined(Q_OS_MAC)
	pluginsDir.cd("kontAMabil");
	pluginsDir.cd("plugins");
#else
	pluginsDir.cdUp();
	pluginsDir.cd("lib");
	pluginsDir.cd("kontAMabil");
	pluginsDir.cd("plugins");
#endif
	report->setUiPluginsPaths(QStringList()<<pluginsDir.absolutePath());
	report->exec();
	delete report;
}

QStringList MeniuRapoarte::menus()
{
	return m_menus;
}

Q_EXPORT_PLUGIN2(meniuRapoarte, MeniuRapoarte);
